document.addEventListener('paste', function (event) {
    if (event.clipboardData || event.originalEvent) {
        var clipboardData = (event.clipboardData || event.originalEvent.clipboardData);
        if (clipboardData.items) {
            var items = clipboardData.items,
                len = items.length,
                blob = null;
            // event.preventDefault();
            for (var i = 0; i < len; i++) {
                if (items[i].type.indexOf("image") !== -1) {
                    blob = items[i].getAsFile();
                }
            }
            if (blob !== null) {
                var reader = new FileReader();
                reader.onload = function (event) {
                    var imgSrc = event.target.result;
                    var img = dataURItoBlob(imgSrc);
                    var guid = new Date().valueOf();
                    var fd = new FormData();
                    fd.append("image", img);
                    fd.append("guid", guid);
                    fd.append('taskId', $("#detailTaskId").val());
                    $.ajax({
                        url:"/file/upload",
                        type:"post",
                        data: fd,
                        cache: false,
                        contentType: false,
                        processData: false,
                        success:function(data){
                            var imagesVal = $(".attachedImg").val();
                            $(".attachedImg").val(imagesVal + "," + data.data.fileName);
                        }
                    });
                    $(".paste-img").append("<img class='attach-img' src='"+imgSrc+"' onclick='imgDetail(this)' data-target='#imgModal'/>");
                };
                reader.readAsDataURL(blob);
            }
        }
    }
});

function dataURItoBlob(dataURI) {
    var byteString = atob(dataURI.split(',')[1]);
    var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
    var ab = new ArrayBuffer(byteString.length);
    var ia = new Uint8Array(ab);
    for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
    }
    var img = new Blob([ab], {type: mimeString});
    img.fimename = (new Date().valueOf()) + ".png";
    return img;
}